/* eslint-disable @typescript-eslint/no-unused-vars */
import { getStaticMenus } from '@/api/menu';
import { constantRouterComponents } from './constantRouterComponents';
import router from '@/router/index';
import { routes } from '@/router/index';
import { notFound } from '@/router/modules/error';
import { Empty } from 'ant-design-vue';
import common from '@/router/common';
import { RouteRecordRaw } from 'vue-router';
import { getSysUserMenus } from '@/api/system/user';
import { storage } from '@/utils/Storage';

/**
 * 异步生成菜单树， 方案二
 * @param dataList
 */
const list2tree = (items, parentId = 0, arr = [], pathPrefix = '') => {
  return items
    .filter((item) => item.pid == parentId)
    .sort((a, b) => a.sort - b.sort)
    .map((item: any) => {
      const { id, icon, menuName, pid, menuUrl } = item;
      let path = menuUrl.startsWith('/') ? menuUrl : '/' + menuUrl;
      path = menuUrl.startsWith(pathPrefix) ? path : pathPrefix + path;
      path = [...new Set(path.split('/'))].join('/');
      // 路由对应的组件
      const component =
        constantRouterComponents[path] || Empty || (() => import('@/views/shared/error/404.vue'));
      return {
        path: path,
        // 路由名称，建议唯一
        name: path || '',
        children: list2tree(items, item.id, [], menuUrl),
        // 该路由对应页面的 组件 (动态加载)
        component: component,
        props: true,
        // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
        meta: {
          title: menuName,
          icon,
          // hiddenHeaderContent: hiddenHeaderContent,
          // permission: item.actions || []menuUrl
          reload: false,
          componentName: component.name,
        },
      };
    });
};

const generatorRedirect = (list) => {
  list.map((item) => {
    if (item.children?.length > 0 && !item.redirect && item.meta.menuLevel < 3) {
      item.redirect = { name: item.children[0].name };
      generatorRedirect(item.children);
    }
  });
};

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
  const userid = storage.get('userid');
  return new Promise((resolve, reject) => {
    // getSysUserMenus(userid)
    getStaticMenus()
      .then((result) => {
        const menuNav: any = [];
        const childrenNav = [];
        //      后端数据, 根级树数组,  根级 PID
        // listToTree(data, childrenNav, 0)
        // rootRouter.children = childrenNav
        menuNav.push(childrenNav);
        // const routeList = list2tree(result.retData)
        const routeList = list2tree(result.retData);
        console.log('=========', routeList);
        generatorRedirect(routeList);
        const layout = routes.find((item) => item.name == 'Layout')!;
        layout.children = [...common, ...routeList];
        // const routes = [...common,...routeList]
        // routes.forEach(item => router.addRoute('Layout', item))
        router.addRoute(layout);
        router.addRoute(notFound);
        resolve(layout.children);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
